import React from 'react';
import { Affix, Icon, Empty } from 'antd';
import s from './index.module.less';
import ChatListItem from '../../components/ChatListItem';
import ProjectItem from '../../components/ProjectItem';
import TaskItem from '../../components/TaskItem';
import UserItem from '../../components/UserItem';
import userServer from '../../services/user';

const { globalSearch } = userServer;

const tags = [
    { icon: 'chat', key: 'chats', name: '群聊' },
    { icon: 'widgets', key: 'projects', name: '项目' },
    { icon: 'tune', key: 'tasks', name: '任务' },
    { icon: 'contacts', key: 'contacts', name: '联系人' }
]

function replaceFun(str, keyword) {
    if (str.indexOf(keyword) > -1) {
        const newStr = str.replace(keyword, `<font color="#1890ff">${keyword}</font>`);
        return newStr;
    } else return str;
}

class GlobalSearchList extends React.Component {

    state = {
        list: []
    }

    componentWillMount() {
        const { searchkey } = this.props;
        this.queryList(searchkey);
    }

    componentWillReceiveProps(nextProps) {
        const { searchkey } = this.props;
        if (nextProps.searchkey && searchkey !== nextProps.searchkey) {
            this.queryList(nextProps.searchkey);
        }
    }

    queryList = async (searchkey) => {
        this.setState({ loading: true });
        const res = await globalSearch({ searchkey, pageindex: 1, pagesize: 99999 });
        if (res) {
            const hasList = tags.map(t => ({
                ...t,
                list: t.key === 'chats' ? res[t.key].dataList : res[t.key]
            })).filter(t => t.list && t.list instanceof Array && t.list.length);
            const list = hasList.map(h => {
                const total = h.list.length;
                const data = { ...h, total };
                if (total > 5) { // 默认显示5项
                    data.showList = h.list.slice(0, 5);
                    data.restList = h.list.slice(5);
                } else {
                    data.showList = h.list;
                }
                return data;
            })
            this.setState({ list, loading: false });
            return;
        }
        this.setState({ loading: false });
    }

    goPage = (index, data) => {
        // console.log(index, data);
        const { ipcRenderer } = window.electron;
        ipcRenderer.send('set-goPage', { index, data });
        this.props.onClear();
    }

    onChatClick = (...params) => {
        const { ipcRenderer } = window.electron;
        const { searchkey } = this.props;
        ipcRenderer.send('create-chatlist-view', { searchkey, groupid: params[1].groupid });
        this.props.onClear();
    }

    renderchatsList = (list) => {
        if (!list) return null;
        const { searchkey } = this.props;
        return (
            list.map((v, i) => (
                <ChatListItem
                    innerRef={(d, id) => this[`node-${id}`] = d}
                    key={`chatItem${i}`}
                    data={v}
                    onClick={this.onChatClick}
                    replaceFun={(str) => replaceFun(str, searchkey)}
                />
            ))
        )
    }

    renderprojectsList = (list) => {
        const { searchkey } = this.props;
        return (
            list.map(v => (
                <ProjectItem
                    innerRef={d => this[`node-${v.recid}`] = d}
                    key={v.recid}
                    data={v}
                    onClick={() => this.goPage(1, v)}
                    replaceFun={(str) => replaceFun(str, searchkey)}
                />
            ))
        )
    }

    rendertasksList = (list) => {
        const { searchkey } = this.props;
        return (
            list.map(v => (
                <TaskItem
                    innerRef={d => this[`node-${v.recid}`] = d}
                    key={v.recid}
                    data={v}
                    onClick={() => this.goPage(2, { ...v, taskid: v.recid })}
                    replaceFun={(str) => replaceFun(str, searchkey)}
                />
            ))
        )
    }

    rendercontactsList = (list) => {
        const { searchkey } = this.props;
        return (
            list.map(v => (
                <UserItem
                    key={v.recid}
                    style={{ paddingLeft: '6px' }}
                    username={v.realname}
                    headimage={v.headimage}
                    onClick={() => this.goPage(3, v)}
                    replaceFun={(str) => replaceFun(str, searchkey)}
                />
            ))
        )
    }

    changeTagStatus = (idx) => {
        const { list } = this.state;
        const newList = list.map((l, i) => {
            const showAll = l.showAll;
            if (i === idx) {
                return { ...l, showAll: !showAll };
            } else return l
        })
        this.setState({ list: newList });
    }

    render() {
        const { list, loading } = this.state;
        return (
            <div className={s.wrapSearchContent}>
                <div className={s.searchContent} ref={node => this.container = node}>
                    {list.length ? (
                        list.map((l, i) => (
                            <div key={l.icon} className={s.tagContent}>
                                <Affix target={() => this.container}>
                                    <h3 className={s.title}>{l.name}</h3>
                                </Affix>
                                <div className={s.wrap}>
                                    {this[`render${l.key}List`](l.showList)}
                                    {l.showAll && this[`render${l.key}List`](l.restList)}
                                    {l.total > 5 ? (
                                        <div
                                            className={s.statusBtn}
                                            onClick={() => this.changeTagStatus(i)}
                                        >
                                            {l.showAll ? '收起' : `显示全部 (${l.total})`}
                                        </div>
                                    ) : null}
                                </div>
                            </div>
                        ))
                    ) : null}
                </div>
                {loading ? (
                    <div className={s.loading}>
                        <Icon type="loading" />
                    </div>
                ) : null}
                {!loading && !list.length ? <div className={s.empty}><Empty description={'无匹配内容'} /></div> : null}
            </div>
        )
    }
}

export default GlobalSearchList